package com.bitejiuyeke.forum.controller;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.config.AppConfig;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.MD5Utils;
import com.bitejiuyeke.forum.utils.StringUtils;
import com.bitejiuyeke.forum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 比特就业课
 */
@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register (@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                               @ApiParam("昵称") @RequestParam("nickname")  @NonNull String nickname,
                               @ApiParam("密码") @RequestParam("password")  @NonNull String password,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat")  @NonNull String passwordRepeat) {
        // 校验密码是否一致
        if (!password.equals(passwordRepeat)) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 构造对象
        User user = new User();
        user.setUsername(username); // 用户名
        user.setNickname(nickname); // 昵称
        // 处理密码
        // 1. 生成盐
        String salt = UUIDUtils.UUID_32();
        // 2. 生成密码的密文
        String encryptPassword = MD5Utils.md5Salt(password, salt);
        // 3. 设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        // 调用Service
        userService.createNormalUser(user);
        // 返回结果
        return AppResult.success("注册成功");
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return AppResult
     */
    @ApiOperation("用户登录")
    @ResponseBody
    @PostMapping("/login")
    public AppResult login (HttpServletRequest request,
                            @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                            @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 调用Service
        User user = userService.login(username, password);
        // 在session中保存当前登录的用户信息
        // 1. 获取session对象
        HttpSession session = request.getSession(true);
        // 2. 把用户信息保存在Session中
        session.setAttribute(AppConfig.SESSION_USER_KEY, user);
        // 返回成功
        return AppResult.success("登录成功");
    }

    /**
     * 退出登录
     * @return AppResult
     */
    @ApiOperation("退出登录")
    @ResponseBody
    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request) {
        // 获取session对象
        HttpSession session = request.getSession(false);
        // 判断session是否有效
        if (session != null) {
            log.debug("注销成功：" + session.toString());
            // 销毁session对象
            session.invalidate();
        }
        // 返回结果
        return AppResult.success("注销成功");
    }

    @ApiOperation("获取用户信息")
    @ResponseBody
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @ApiParam("用户Id") @RequestParam(value = "id", required = false) Long id) {
        // 定义返回的User对象
        User user;
        // 根据用传入的Id值，获取User对象的方式
        if (id == null) {
            // 获取session
            HttpSession session = request.getSession(false);
            // 从session中获取用户对象
            user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        } else {
            // 从数据库中查询
            user = userService.selectById(id);
        }
        // 返回结果
        return AppResult.success(user);
    }


    /**
     * 修改个人信息
     * @param username 用户名(用于登录)
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话
     * @param remark 个人简介
     * @return AppResult<User>
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo (HttpServletRequest request,
                                       @ApiParam("用户名(用于登录)") @RequestParam(value = "username", required = false) String username,
                                       @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                       @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                       @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                       @ApiParam("电话") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                       @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        // 校验参数不能全部为空
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
        && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
        && StringUtils.isEmpty(remark) && gender == null) {
            // 返回提示
            return AppResult.failed("要修改的信息不能为空");
        }
        // 获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);

        // 构造User对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setEmail(email); // 邮箱
        updateUser.setRemark(remark); // 个人简介

        // 调用Service
        userService.modifyInfo(updateUser);
        // 查询修改后的用户数据
        user = userService.selectById(user.getId());
        // 把User对象设置回session
        session.setAttribute(AppConfig.SESSION_USER_KEY, user);
        // 返回更新后的User对象
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 新密码与确认密码必须相等
        if (newPassword.equals(passwordRepeat) == false) {
            // 返回提示
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        // 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 销毁当前的session
        session.invalidate();
        // 返回结果
        return AppResult.success();
    }
}
